package servletPackage;

import inspur.dao.BookDao;
import inspur.dao.CookieDao;
import inspur.dao.UserDao;
import inspur.entity.BookObject;
import inspur.entity.CookieTokenObject;
import inspur.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UploadBookServlet")
public class DeleteBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
        String bookId=request.getParameter("bookId");
        if (bookId==null){
            out.print("提醒，需要填写一个书籍编号");
            return;
        }else{
            if (bookId.equals("")){
                out.print("提醒，需要填写一个书籍编号");
                return;
            }
        }
        //
        String userid=CookieDao.getCookieItemValue(request,"userid");
        if (userid==null){
            out.print("删除失败，原因：你没有登录");
        }else{
            System.out.print(userid);
            User myUser=UserDao.getUserByUserId(userid);
            CookieTokenObject cto= CookieDao.CreatCookieTokenObject(request);
            System.out.print(myUser.getPassword());
            boolean ctoIsOk=CookieDao.isTrueToken(cto,myUser.getPassword(),request);
            if (ctoIsOk&&myUser.getIdentity().equals("admin")){
                BookObject _book=BookDao.SelectBookById(bookId);
                if (_book.getStatus().equals("0")){
                    out.println("移除图书失败，原因：该图书处于被借（占有）状态，无法被移除。");
                    out.println("当该图书处于未被借的状态时，才能被移除");
                }else{
                    int flag=BookDao.DeleteBook(bookId);
                    if (flag==2){
                        out.print("success");
                        System.out.print("success");
                    }else if(flag==3) {
                        out.print("删除失败，原因：图书编号重复或丢失");
                        System.out.print("3");
                    }else{
                        out.print("数据库出现未知错误，请联系管理员");
                        System.out.print("x");
                    }
                }

            }else {
                out.print("你没有权限处理这个请求，你必须是管理员才能删除图书");
            }
        }
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
